﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MvcEngine.Core.Utils
{
    public static class CacheUtils
    {
        private const string KeySuffixSeparator = ":::";

        /// <summary>
        /// Extend key for CacheManager.
        /// </summary>
        /// <param name="key">The input key.</param>
        /// <param name="cacheKey">Used for generation additional part.</param>
        /// <returns>Extended key.</returns>
        public static string MakeCacheKey(string key, CacheKeys cacheKey)
        {
            return key + GenerateKeySuffix(cacheKey);
        }

        public static string MakeCacheKey(string key, object value, CacheKeys cacheKey)
        {
            return string.Format(key, value.ToString()) + GenerateKeySuffix(cacheKey);
        }

        private static string GenerateKeySuffix(CacheKeys cacheKey)
        {
            StringBuilder keySuffix = new StringBuilder();

            if ((cacheKey & CacheKeys.Site) == CacheKeys.Site)
                keySuffix.Append(KeySuffixSeparator + SiteContext.Current.Site.Id.ToString());

            if ((cacheKey & CacheKeys.User) == CacheKeys.User)
                keySuffix.Append(KeySuffixSeparator + UserContext.Current.User.Id.ToString());

            return keySuffix.ToString();
        }
    }
}
